package common;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public abstract class BaseProcessor implements Processor{
	protected static String mask = ".";

	public Object invoke(Object obj, String methodName, Class[] clazz,
			Object[] params) throws InvokeException{
		Class objClazz = obj.getClass();
		
		Object returnVal = null;
		try {
			beforeInvoke(objClazz.getSimpleName(), methodName);
			System.out.println("Begin invoke "+objClazz.getSimpleName()+mask+methodName+" ...");

			returnVal = objClazz.getDeclaredMethod(methodName, clazz).invoke(obj, params);
			
			System.out.println("Invoke "+objClazz.getSimpleName()+mask+methodName+" Completely");
			if(returnVal != null){
				System.out.println(objClazz.getSimpleName()+mask+methodName+" returns "+returnVal);
			}
			afterInvoke(objClazz.getSimpleName(), methodName);
			System.out.println("-----------------------------------------------------");
		} catch (Exception e) {
			throw new InvokeException(objClazz.getSimpleName(), methodName, e);
		}
		
		return returnVal;
	}
	
	protected abstract void beforeInvoke(String className, String methodName);
	protected abstract void afterInvoke(String className, String methodName);

	private Object getObjectByConstructor(String className, Class[] argsClazz, Object[] args){
		Object obj = null;

		try {
			Class clazz = Class.forName(className);
			Constructor constructor = clazz.getDeclaredConstructor(argsClazz);
			obj = constructor.newInstance(args);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}

}
